#!/bin/bash

UPDATE_INFO="/var/lib/lastore/update_infos.json"

function prepare()
{
    # The unit is typically launched by apt hooks,
    # so we just directly exit failed when the apt-get is still running, and restart it after 1 seconds.
    if /usr/bin/pgrep apt-get > /dev/null; then
        echo "apt-get is running, please try it later"
        exit 1;
    fi

    if [ "$(/usr/bin/busctl get-property com.deepin.lastore /com/deepin/lastore com.deepin.lastore.Manager SystemOnChanging)" != "b false" ]; then
        echo "system is on changing, please try it later"
        exit -1;
    fi
}

function systemd_build_system_info()
{
    systemctl start lastore-build-system-info.service
}

function build_system_info_now()
{
    /usr/bin/lastore-tools update -j=update_infos -output=$UPDATE_INFO
    /usr/bin/lastore-tools update -j=desktop -o /var/lib/lastore/
    /var/lib/lastore/scripts/build_safecache.sh > /dev/null
}


# If both apt and dpkg hasn't modified after $UPDATE_INFO created, we doesn't need do anything.
if [[ -f "$UPDATE_INFO" ]] &&
       [[ $(find /var/lib/apt/lists -maxdepth 1 -type f -\! -name "lock") != "" ]] &&
       [[ "$UPDATE_INFO" -nt "/var/lib/dpkg/status" ]] &&
       [[ "$UPDATE_INFO" -ot "/proc/self"  ]] &&
       [[ $(find /var/lib/apt/lists -maxdepth 1 -type f -newercm "$UPDATE_INFO" ) == "" ]] ;then
	# trigger lastore-daemon update handler
	touch "$UPDATE_INFO"
    exit 0
fi

#We should clean the update_infos.json early, otherwise
#actions, like systemctl stop, reboot immediately after apt-get
#would cause the update_infos.json invalid.
[ -f $UPDATE_INFO ] && rm $UPDATE_INFO

case "$1" in
    "-now")
        prepare
        build_system_info_now
        ;;
    *)
        if [[ -S /var/run/systemd/notify ]]; then
            systemd_build_system_info
        else
            build_system_info_now
        fi
        ;;
esac
